package com.sitecsys.controller;


import com.auth0.jwt.interfaces.DecodedJWT;
import com.sitecsys.config.Result;
import com.sitecsys.mapper.TbUserMapper;
import com.sitecsys.pojo.TbUser;
import com.sitecsys.service.TbUserService;
import com.sitecsys.utils.JwtUtils;
import javafx.scene.image.Image;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LHB
 * @since 2024-01-06
 */
@RestController
@RequestMapping("/api/tbuser")
public class TbUserController {

    @Autowired
    private TbUserService tbUserService;

    @Resource
    private TbUserMapper tbUserMapper;
    @PostMapping ("/login")
    public Result login(@RequestBody JSONObject jsonObj ){
       return tbUserService.login(jsonObj);
    }

    @PostMapping("/register")
    public Result register(@RequestBody JSONObject jsonObj){
        return tbUserService.register(jsonObj);
    }

    @PostMapping("/userInfo")
    public Result userInfo(HttpServletRequest request){
        return tbUserService.getUserByPhone(request);
    }

    @PostMapping("/getUserByPhoneAndName")
    public Result getUserByPhoneAndName(@RequestBody JSONObject jsonObj){
        return tbUserService.getUserByPhoneAndName(jsonObj);
    }

    @PostMapping("/CheckUser")
    public Result CheckUser(@RequestBody JSONObject jsonObj){
        return tbUserService.CheckUserByPhone(jsonObj);
    }

    @PostMapping("/updatePassWord")
    public Result updatePassWord(@RequestBody JSONObject jsonObj){
        return tbUserService.updatePassword(jsonObj);
    }
    @PostMapping("/upload-image")
    public Result uploadImage(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws Exception {
        if (!file.isEmpty()) {
            try {
                // 将MultipartFile转换为byte数组
                byte[] imageData = file.getBytes();

                String token = request.getHeader("access-token");
                DecodedJWT jwt = JwtUtils.getTokenInfo(token);
                String phone = jwt.getClaim("phone").asString();
                Boolean flag = tbUserMapper.updateUserByPhone(phone, imageData);

                return Result.success(flag);

            } catch (IOException e) {
                // 图片读取失败时的异常处理
                return Result.error("Failed to read the uploaded file");
            }
        } else {
            return Result.error("Please select a file to upload");
        }
    }
}

